﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Honestysoft.Baseframework.WebUI;
using System.Configuration;
using Honestysoft.Financing.Model;
using Honestysoft.DictionaryHelper;
using System.Data.Common;
using Honestysoft.BaseObject;
using Honestysoft.Baseframework.Model;

namespace Honestysoft.Financing.WebUI.Module.Audit
{
    public partial class FirstProjDocReceive : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControl();
                Bind();
            }
        }

        private void Bind()
        {

            hidContractID.Value = Request.QueryString["ContractID"];
            dtpReceiveDate.Text = DateTime.Today.ToString("yyyy-MM-dd");

            txtToCompany.Text = ConfigurationManager.AppSettings["YZName"];

            txtToEmployeeName.Text = UserLoginer.LoginUser.Name;
            hidToEmployee.Value = UserLoginer.LoginUser.ID;

            txtCode.Text = new Honestysoft.Financing.BusinessLogic.Audit(Globals.CurrentConnStringName).GetNextDocReceiveCode();
        }
        private DataTable dtYesNo = null;
        private void BindRadioList(RadioButtonList rbl)
        {
            rbl.DataSource = dtYesNo;
            rbl.DataTextField = "Text";
            rbl.DataValueField = "Value";
            rbl.DataBind();
            rbl.SelectedIndex = 0;
        }

        private void BindControl()
        {
            dtYesNo = new DataTable();
            dtYesNo.Columns.Add("Text", typeof(string));
            dtYesNo.Columns.Add("Value", typeof(string));
            DataRow dr = dtYesNo.NewRow();
            dr["Text"] = "有  ";
            dr["Value"] = "1";
            dtYesNo.Rows.Add(dr);
            dr = dtYesNo.NewRow();
            dr["Text"] = "无";
            dr["Value"] = "0";
            dtYesNo.Rows.Add(dr);

            BindRadioList(rblContDoc1);
            BindRadioList(rblContDoc2);
            BindRadioList(rblContDoc3);
            BindRadioList(rblContDoc4);
            BindRadioList(rblContDoc5);
            BindRadioList(rblContDoc6);
            BindRadioList(rblContDoc7);
            BindRadioList(rblContDoc8);
            BindRadioList(rblContDoc9);
            BindRadioList(rblCD_One);

            BindRadioList(rblProjDoc1);
            BindRadioList(rblProjDoc2);
            BindRadioList(rblProjDoc3);
            BindRadioList(rblProjDoc4);
            BindRadioList(rblProjDoc5);
            BindRadioList(rblProjDoc6);
            BindRadioList(rblProjDoc7);
            BindRadioList(rblProjDoc8);
            BindRadioList(rblProjDoc9);
            BindRadioList(rblProjDoc10);
            BindRadioList(rblPD_One);

            BindRadioList(rblZJDWDoc1);
            BindRadioList(rblZJDWDoc2);
            BindRadioList(rblZJDWDoc3);
            BindRadioList(rblZJDWDoc4);
            BindRadioList(rblZD_One);

            DataTable dt = new Honestysoft.Financing.BusinessLogic.Reports(Globals.CurrentConnStringName).GetAllCompany();
            BindCompany(ddlContractor, dt);
            BindCompany(ddlFromCompany, dt);
            BindCompany(ddlOwner, dt);
            BindCompany(ddlOwner971, dt);

            txtToCompany.Enabled = false;

            //ControlHelper.BindEnum(ddlDocRecieveStatus, "DocRecieveStatus");//此处最好改成typeof(EnumItem.XXX)
        }

        private void BindCompany(DropDownList ddl, DataTable dt)
        {
            ddl.DataTextField = "CompName";
            ddl.DataValueField = "ID";
            ddl.DataSource = dt;
            ddl.DataBind();
        }



        protected void btnOK_Click(object sender, EventArgs e)
        {
            #region 单位信息
            //如果公司的ID和text相同，则是新单位
            List<Org_Company> lsNewCompany = new List<Org_Company>();
            Org_Company company = null;
            string maxCompCode = new Honestysoft.Financing.BusinessLogic.Reports(Globals.CurrentConnStringName).GetMaxCompanyCode();            
            if (hidContractorID.Value == hidContractorName.Value)//表示新增
            {
                if (!lsNewCompany.Exists((Org_Company find) => find.CompName == hidContractorID.Value))
                {
                    company = GetNewCompany(maxCompCode, ConfigurationManager.AppSettings["CompanyCategory_SG"], hidContractorID.Value);
                    lsNewCompany.Add(company);
                    maxCompCode = company.CompCode;
                }
            }
            if (hidOwnerID.Value == hidOwnerName.Value)//表示新增
            {
                if (!lsNewCompany.Exists((Org_Company find) => find.CompName == hidOwnerID.Value))
                {
                    company = GetNewCompany(maxCompCode, ConfigurationManager.AppSettings["CompanyCategory_JS"], hidOwner971ID.Value);
                    lsNewCompany.Add(company);
                    maxCompCode = company.CompCode;
                }
            }
            if (hidFromCompanyID.Value == hidFromCompanyName.Value)//表示新增
            {
                if (!lsNewCompany.Exists((Org_Company find) => find.CompName == hidFromCompanyID.Value))
                {
                    company = GetNewCompany(maxCompCode, ConfigurationManager.AppSettings["CompanyCategory_JS"], hidFromCompanyID.Value);
                    lsNewCompany.Add(company);
                    maxCompCode = company.CompCode;
                }
            }
            if (hidOwner971ID.Value == hidOwner971Name.Value)//表示新增
            {
                if (!lsNewCompany.Exists((Org_Company find) => find.CompName == hidOwner971ID.Value))
                {
                    company = GetNewCompany(maxCompCode, ConfigurationManager.AppSettings["CompanyCategory_XM"], hidOwner971ID.Value);
                    lsNewCompany.Add(company);
                    maxCompCode = company.CompCode;
                }
            }
            #endregion

            BD_Project project = new BD_Project();
            project.Code = txtProjectCode.Text;
            project.ConfirmOpinion="";
            project.FCode = "未设置";
            project.FinInvestment = 0;
            project.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
            project.Investment = 0;
            project.InvestmentType = ((int)Honestysoft.Financing.Model.EnumItem.InvestmentType.Budget).ToString();
            project.IsDymSplit = false;
            project.IsInit = false;
            project.IsSplit = false;
            project.Name = txtProjectName.Text;
            if (hidOwnerID.Value == hidOwnerName.Value)
            {
                project.Owner = lsNewCompany.Find((Org_Company find) => find.CompName == hidOwnerID.Value).ID;
            }
            else
            {
                project.Owner = hidOwnerID.Value;
            }
            if (hidOwner971ID.Value == hidOwner971Name.Value)
            {
                project.Owner971 = lsNewCompany.Find((Org_Company find) => find.CompName == hidOwner971ID.Value).ID;
            }
            else
            {
                project.Owner971 = hidOwner971ID.Value;
            }
            project.ProjectCategory = ConfigurationManager.AppSettings["UnknowProjectCategory"];
            List<Sys_Dictionary> lsProjectCategory = Honestysoft.DictionaryHelper.DictionaryInstance.GetDictionaryList("ProjectCategory");
            if (lsProjectCategory != null && lsProjectCategory.Count > 0)
            {                
                foreach (Sys_Dictionary item in lsProjectCategory)
                {
                    if (item.DictName == hidOwner971Name.Value)
                    {
                        project.ProjectCategory = item.DictValue;
                        break;
                    }
                }
            }
            project.SN = "未设置";
            project.SortCode = 0;
            project.Stage = 0;
            project.TotalCapitalAmount = 0;
            project.ConType = ((int)Honestysoft.Financing.Model.EnumItem.ConType.UnKnow).ToString();
            project.ProjectPhase = ((int)Honestysoft.Financing.Model.EnumItem.ProjectPhase.UnKnow).ToString();


            BD_Contract contract = new BD_Contract();
            contract.BankAccount = "";
            contract.BankName = "";
            contract.ChangePrice = 0;
            contract.Code = "未设置";
            contract.ConfirmOpinion = "";
            contract.ContractCategory = ConfigurationManager.AppSettings["UnknowContractCategory"];
            if (hidContractorID.Value == hidContractorName.Value)
            {
                contract.Contractor = lsNewCompany.Find((Org_Company find) => find.CompName == hidContractorID.Value).ID;
            }
            else
            {
                contract.Contractor = hidContractorID.Value;
            }
            contract.CreateTime = DateTime.Now;
            contract.Creator = UserLoginer.LoginUser.ID;
            contract.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
            contract.IsInit = false;
            contract.IsZD = false;
            contract.Name = txtContractName.Text;
            contract.ProjectID = project.ID;
            contract.TotalPrice = 0;

            Bu_DocReceive obj = new Bu_DocReceive();
            obj.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
            obj.Code = txtCode.Text;
            obj.ContractID = contract.ID;
            if (numAmount.Text.Trim().Length > 0) { obj.Amount = Convert.ToDecimal(numAmount.Text); }
            obj.Other = txtOther.Text;
            if (hidFromCompanyID.Value == hidFromCompanyName.Value)
            {
                obj.FromCompany = lsNewCompany.Find((Org_Company find) => find.CompName == hidFromCompanyID.Value).ID;
            }
            else
            {
                obj.FromCompany = hidFromCompanyID.Value;
            }
            obj.FromEmployee = txtFromEmployee.Text;
            obj.ToCompany = ConfigurationManager.AppSettings["YZID"];
            obj.ToEmployee = UserLoginer.LoginUser.ID;
            obj.ToEmployeeName = txtToEmployeeName.Text;
            if (dtpReceiveDate.Text.Trim().Length > 0) { obj.ReceiveDate = Convert.ToDateTime(dtpReceiveDate.Text); }
            obj.CreateTime = DateTime.Now;
            obj.Creator = UserLoginer.LoginUser.ID;
            obj.FromEmployeePhone = txtFromEmployeePhone.Text;
            obj.DocRecieveStatus = ((int)Honestysoft.Financing.Model.EnumItem.DocRecieveStatus.Accept).ToString();

            obj.IsCD1 = rblContDoc1.SelectedValue == "1";
            obj.IsCD2 = rblContDoc2.SelectedValue == "1";
            obj.IsCD3 = rblContDoc3.SelectedValue == "1";
            obj.IsCD4 = rblContDoc4.SelectedValue == "1";
            obj.IsCD5 = rblContDoc5.SelectedValue == "1";
            obj.IsCD6 = rblContDoc6.SelectedValue == "1";
            obj.IsCD7 = rblContDoc7.SelectedValue == "1";
            obj.IsCD8 = rblContDoc8.SelectedValue == "1";
            obj.IsCD9 = rblContDoc9.SelectedValue == "1";
            obj.IsCD_One = rblZD_One.SelectedValue == "1";

            obj.IsPD1 = rblProjDoc1.SelectedValue == "1";
            obj.IsPD2 = rblProjDoc2.SelectedValue == "1";
            obj.IsPD3 = rblProjDoc3.SelectedValue == "1";
            obj.IsPD4 = rblProjDoc4.SelectedValue == "1";
            obj.IsPD5 = rblProjDoc5.SelectedValue == "1";
            obj.IsPD6 = rblProjDoc6.SelectedValue == "1";
            obj.IsPD7 = rblProjDoc7.SelectedValue == "1";
            obj.IsPD8 = rblProjDoc8.SelectedValue == "1";
            obj.IsPD9 = rblProjDoc9.SelectedValue == "1";
            obj.IsPD10 = rblProjDoc10.SelectedValue == "1";
            obj.IsPD_One = rblPD_One.SelectedValue == "1";

            obj.IsZD1 = rblZJDWDoc1.SelectedValue == "1";
            obj.IsZD2 = rblZJDWDoc2.SelectedValue == "1";
            obj.IsZD3 = rblZJDWDoc3.SelectedValue == "1";
            obj.IsZD4 = rblZJDWDoc4.SelectedValue == "1";
            obj.IsZD_One = rblZD_One.SelectedValue == "1";

            obj.CD1 = txtContDoc1.Text;
            obj.CD2 = txtContDoc2.Text;
            obj.CD3 = txtContDoc3.Text;
            obj.CD4 = txtContDoc4.Text;
            obj.CD5 = txtContDoc5.Text;
            obj.CD6 = txtContDoc6.Text;
            obj.CD7 = txtContDoc7.Text;
            obj.CD8 = txtContDoc8.Text;
            obj.CD9 = txtContDoc9.Text;
            obj.CD_One = txtCD_One.Text;

            obj.PD1 = txtProjDoc1.Text;
            obj.PD2 = txtProjDoc2.Text;
            obj.PD3 = txtProjDoc3.Text;
            obj.PD4 = txtProjDoc4.Text;
            obj.PD5 = txtProjDoc5.Text;
            obj.PD6 = txtProjDoc6.Text;
            obj.PD7 = txtProjDoc7.Text;
            obj.PD8 = txtProjDoc8.Text;
            obj.PD9 = txtProjDoc9.Text;
            obj.PD10 = txtProjDoc10.Text;
            obj.PD_One = txtPD_One.Text;

            obj.ZD1 = txtZJDWDoc1.Text;
            obj.ZD2 = txtZJDWDoc2.Text;
            obj.ZD3 = txtZJDWDoc3.Text;
            obj.ZD4 = txtZJDWDoc4.Text;
            obj.ZD_One = txtZD_One.Text;

            DbTransaction transaction = Honestysoft.BaseLibrary.Data.DatabaseProvider.GetDbTransaction(Globals.CurrentConnStringName);
            DbConnection connection = transaction.Connection;
            try
            {                
                if (lsNewCompany.Count > 0)
                {
                    new BaseBusinessLogic<Org_Company>(Globals.CurrentConnStringName).CreateEntitys(lsNewCompany, transaction);
                }
                new BaseBusinessLogic<BD_Project>(Globals.CurrentConnStringName).CreateEntity(project, transaction);
                new BaseBusinessLogic<BD_Contract>(Globals.CurrentConnStringName).CreateEntity(contract, transaction);
                new BaseBusinessLogic<Bu_DocReceive>(Globals.CurrentConnStringName).CreateEntity(obj, transaction);
                transaction.Commit();
                Response.Redirect("DocReceivePrint.aspx?ID=" + obj.ID + "&FunctionID=" + Request.QueryString["FunctionID"] + "&IsUse=0&IsNew=1");
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                Honestysoft.BaseLibrary.ExceptionHandling.ExceptionHelper.ExceptionDistribute(ex, false);
                ScriptHelper.Window.Alert("保存失败！" + ex.Message);
            }
            finally
            {
                connection.Close();
            }
        }

        private Org_Company GetNewCompany(string maxCompCode,string categoryId,string compName)
        {
            Org_Company company = new Org_Company();
            company.CategoryID = categoryId;
            if (maxCompCode == "")
            {
                maxCompCode = new Honestysoft.Financing.BusinessLogic.Reports(Globals.CurrentConnStringName).GetMaxCompanyCode();
            }
            int compCode = Convert.ToInt32(maxCompCode.Substring(3)) + 1;
            maxCompCode = "GS-" + compCode.ToString().PadLeft(4, '0');
            company.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
            company.CompCode = maxCompCode;
            company.CompName = compName;
            company.IsValid = true;
            company.IsInner = false;
            company.SortCode = compCode;
            return company;
        }
    }
}